package rexsee.barcode;

import java.util.Hashtable;
import java.util.concurrent.CountDownLatch;

import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.google.zxing.DecodeHintType;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;

public class DecodeThread extends Thread {

	public static final String BARCODE_BITMAP = "barcode_bitmap";

	private final BarcodeCaptureDialog mDialog;
	private final Hashtable<DecodeHintType, Object> hints;
	private Handler handler;
	private final CountDownLatch handlerInitLatch;

	public DecodeThread(BarcodeCaptureDialog dialog) {
		mDialog = dialog;
		handlerInitLatch = new CountDownLatch(1);
		hints = new Hashtable<DecodeHintType, Object>(3);
		hints.put(DecodeHintType.POSSIBLE_FORMATS, mDialog.mDecodeFormats);
		if (mDialog.mCharacterSet != null) {
			hints.put(DecodeHintType.CHARACTER_SET, mDialog.mCharacterSet);
		}
		//hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, resultPointCallback);
		hints.put(DecodeHintType.NEED_RESULT_POINT_CALLBACK, new ResultPointCallback() {
			@Override
			public void foundPossibleResultPoint(ResultPoint point) {
				try {
					mDialog.mViewfinderView.addPossibleResultPoint(point);
				} catch (Exception e) {
					Toast.makeText(mDialog.getContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
				}
			}
		});
	}
	public Handler getHandler() {
		try {
			handlerInitLatch.await();
		} catch (InterruptedException ie) {
		}
		return handler;
	}

	@Override
	public void run() {
		try {
			Looper.prepare();
			handler = new DecodeHandler(mDialog, hints);
			handlerInitLatch.countDown();
			Looper.loop();
		} catch (Exception e) {
			Toast.makeText(mDialog.getContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
		}
	}

}
